package com.gzdh.tang.cupboard.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gzdh.tang.cupboard.entity.CupboardCabInfo;
import com.gzdh.tang.cupboard.entity.CupboardSell;
import com.gzdh.tang.cupboard.service.CupboardCabInfoService;
import com.gzdh.tang.cupboard.service.CupboardSellService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.alipay.demo.trade.utils.Utils.sleep;

@Slf4j
@RestController
@RequestMapping("api/CCupboard")
public class CCupboardController {

    @Autowired
    CupboardCabInfoService cupboardCabInfoService;

    @Autowired
    CupboardSellService cupboardSellService;


    @PostMapping("vending_machine")
    public Map<String, String> cupboardMsg(HttpServletRequest request) {

        String funCode = request.getParameter("FunCode");
        if ("1000".equals(funCode)) {
            //上传货道信息
            return updateChannelMsg(request);

        } else if ("4000".equals(funCode)) {
            log.info("收到心跳");
            for (int i = 0; i < 5; i++) {
                try {
                    Map<String, String> resTemp = mstscSell(request);
                    if (resTemp != null) {
                        return resTemp;
                    }
                    sleep(5000);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return null;

        } else if ("5000".equals(funCode)) {

//            出货上报
            return sellFlush(request);

        } else if ("2000".equals(funCode)) {

//            通过取货码出货
            return pickingQr(request);
        } else if ("5001".equals(funCode)) {

        }

        return null;
    }


    /**
     * 上传货道信息接口
     *
     * @param request
     * @return
     */
    private Map<String, String> updateChannelMsg(HttpServletRequest request) {
        Map<String, String> resMap = new HashMap<>();

//        机器号
        String machineId = request.getParameter("MachineID");
//        序列号，机器生成
        String tradeNo = request.getParameter("TradeNo");
//        货道号
        String slotNo = request.getParameter("SlotNo");
//        按键号
        int keyNum = getInt(request.getParameter("KeyNum"));
//        货道状态
        int status = getInt(request.getParameter("Status"));
//        现存
        int quantity = getInt(request.getParameter("Quantity"));
//        现存
        int stock = getInt(request.getParameter("Stock"));
//        容量
        int capacity = getInt(request.getParameter("Capacity"));
//        商品ID
        String productId = request.getParameter("ProductID");
//        单价
        String price = request.getParameter("Price");
//        商品类型
        String type = request.getParameter("Type");
//        商品介绍
        String introduction = request.getParameter("Introduction");
//        商品名称
        String name = request.getParameter("Name");

        CupboardCabInfo cupboardCabInfo = cupboardCabInfoService.getOne(new QueryWrapper<CupboardCabInfo>()
                .lambda().eq(CupboardCabInfo::getMachineId, machineId)
                .eq(CupboardCabInfo::getSlotNo, slotNo));
        if (cupboardCabInfo == null) {
            cupboardCabInfo = new CupboardCabInfo();
            cupboardCabInfo.setMachineId(machineId);
            cupboardCabInfo.setSlotNo(slotNo);
            cupboardCabInfo.setKeyNum(keyNum);
            cupboardCabInfo.setStatus(status);
            cupboardCabInfo.setQuantity(quantity);
            cupboardCabInfo.setStock(stock);
            cupboardCabInfo.setCapacity(capacity);
            cupboardCabInfo.setProductId(productId);
            cupboardCabInfo.setPrice(price);
            cupboardCabInfo.setType(type);
            cupboardCabInfo.setIntroduction(introduction);
            cupboardCabInfo.setName(name);
            cupboardCabInfoService.save(cupboardCabInfo);
        } else {
            cupboardCabInfo.setKeyNum(keyNum);
            cupboardCabInfo.setStatus(status);
            cupboardCabInfo.setQuantity(quantity);
            cupboardCabInfo.setStock(stock);
            cupboardCabInfo.setCapacity(capacity);
            cupboardCabInfo.setProductId(productId);
            cupboardCabInfo.setPrice(price);
            cupboardCabInfo.setType(type);
            cupboardCabInfo.setIntroduction(introduction);
            cupboardCabInfo.setName(name);
            cupboardCabInfoService.updateById(cupboardCabInfo);
        }
        resMap.put("Status", "0");
        resMap.put("SlotNo", slotNo);
        resMap.put("TradeNo", tradeNo);
        resMap.put("Err", "success");
        return resMap;
    }


    /**
     * 取货码
     *
     * @param request
     * @return
     */
    private Map<String, String> pickingQr(HttpServletRequest request) {
        Map<String, String> resMap = new HashMap<>();
        //机器号
        String machineId = request.getParameter("MachineID");
//        序列号，机器生成
        String tradeNo = request.getParameter("MachineID");
//        货道号
        String slotNo = request.getParameter("SlotNo");
//        取货码
        String sessionCode = request.getParameter("SessionCode");
//        价格
        String price = request.getParameter("Price");
//        卡号
        String account = request.getParameter("Account");
//        VMC密码
        String password = request.getParameter("PWS");
        CupboardSell cupboardSell = cupboardSellService.getOne(new QueryWrapper<CupboardSell>().lambda()
                .eq(CupboardSell::getMachineId, machineId)
                .eq(CupboardSell::getStatus, 0)
                .eq(CupboardSell::getSessionCode, sessionCode));
        if (cupboardSell == null) {
            //查找不到取货码
            resMap.put("Status", "1");
            resMap.put("Err", "取货码错误");
            resMap.put("TradeNo", tradeNo);
            return resMap;
        } else {
            resMap.put("Status", "0");
            resMap.put("TradeNo", tradeNo);
            resMap.put("Err", "操作成功");
            resMap.put("SlotNo", cupboardSell.getSlotNo());
            cupboardSellService.lambdaUpdate().set(CupboardSell::getStatus, 1).eq(CupboardSell::getId, cupboardSell.getId());
            return resMap;
        }


    }


    /**
     * 出货完毕后反馈
     *
     * @param request
     * @return
     */
    private Map<String, String> sellFlush(HttpServletRequest request) {
        Map<String, String> resMap = new HashMap<>();
//        柜子编号
        String machineId = request.getParameter("MachineID");
//        支付类型
        String payType = request.getParameter("PayType");
//        订单号
        String tradeNo = request.getParameter("TradeNo");
//        货道号
        String slotNo = request.getParameter("SlotNo");
//        出货状态
        int status = getInt(request.getParameter("Status"));
//        出货时间
        String time = request.getParameter("Time");
//        金额
        String amount = request.getParameter("Amount");
//        商品编号
        String productId = request.getParameter("ProductID");
//        商品名称
        String name = request.getParameter("Name");
//        商品类型
        String type = request.getParameter("Type");
        CupboardSell cupboardSell = cupboardSellService.getOne(new QueryWrapper<CupboardSell>().lambda()
                .eq(CupboardSell::getTradeNo, tradeNo));
        if (cupboardSell != null) {
//            标志已出货
            cupboardSellService.lambdaUpdate().set(CupboardSell::getStatus, status)
                    .set(CupboardSell::getSellTime, time)
                    .eq(CupboardSell::getId, cupboardSell.getId());
        } else {
            SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-mm-dd HH:mm:ss");
            cupboardSell = new CupboardSell();
            cupboardSell.setSellTime(simpleDateFormat.format(new Date()));
            cupboardSell.setStatus(1);
            cupboardSell.setProductId(productId);
            cupboardSell.setTradeNo(tradeNo);
            cupboardSell.setMachineId(machineId);
            cupboardSell.setPayType(payType);
            cupboardSell.setSlotNo(slotNo);
            cupboardSell.setSellTime(time);
            cupboardSellService.save(cupboardSell);
        }
        resMap.put("Status", "0");
        resMap.put("TradeNo", tradeNo);
        resMap.put("SlotNo", slotNo);
        resMap.put("Err", "success");
        return resMap;
    }


    /**
     * 远程售卖下发
     *
     * @param request
     * @return
     */
    private Map<String, String> mstscSell(HttpServletRequest request) {
        Map<String, String> resMap = new HashMap<>();
        String machineId = request.getParameter("MachineID");
        CupboardSell cupboardSell = cupboardSellService.getCupboardSell(machineId);
        if (cupboardSell == null) {
            return null;
        }
        cupboardSellService.lambdaUpdate().set(CupboardSell::getStatus, 0).eq(CupboardSell::getId, cupboardSell.getId());
        resMap.put("Status", "0");
        resMap.put("NsgType", "0");
        resMap.put("TradeNo", cupboardSell.getTradeNo());
        resMap.put("SlotNo", cupboardSell.getSlotNo());
        resMap.put("Err", "成功");
        resMap.put("ProductID", cupboardSell.getProductId());
        return resMap;
    }


    private int getInt(String param) {
        try {
            if (StringUtils.isEmpty(param)) {
                return 0;
            } else {
                return Integer.valueOf(param);
            }
        } catch (Exception e) {
            return 0;
        }
    }
}
